import Vue from "vue";
import Vuex from "vuex";
import {getRequest} from "@/utils/api";
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

Vue.use(Vuex);


const now = new Date();

const store =  new Vuex.Store({
    state:{
        routes:[],
        sessions:[],
        admins: [],
        currentAdmin:JSON.parse(window.sessionStorage.getItem('user')),
        currentSession:-1,
        filterKey:'',
        stomp:null
    },

    mutations:{
        INIT_ADMIN(state,admin){
            state.currentAdmin = admin;
        },
        initRoutes(state, data){
            state.routes = data
        },
        changeCurrentSession (state,currentSession) {
            state.currentSession = currentSession;
        },
        addMessage (state,msg) {
            state.sessions[state.currentSession-1].messages.push({
                content:msg,
                date: new Date(),
                self:true
            })
        },
        INIT_DATA (state) {
            // let data = localStorage.getItem('vue-chat-session');
            // //console.log(data)
            // if (data) {
            //     state.sessions = JSON.parse(data);
            // }
        },
        INIT_ADMINS (state, data){
            state.admins = data;
        }
    },

    actions:{
        connect(context){
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            let token = window.sessionStorage.getItem('tokenStr');
            // 连接端点
            context.state.stomp.connect({'Auth-Token':token},success=>{
                // 连接成功订阅队列
                context.state.stomp.subscribe('/user/queue/chat',msg =>{
                    console.log(msg.body);
                })
            },error=>{
                console.log('websocket连接失败')
            })
        },
        initData (context) {
            // context.commit('INIT_DATA')
            // 访问后端接口获得admin列表
            getRequest('/chat/admin').then(resp =>{
                if (resp){
                    // 触发
                    context.commit('INIT_ADMINS',resp)
                }
            })
        }
    }
})

store.watch(function (state) {
    return state.sessions
},function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;